package com.xb.p24_servicelife;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

    MediaPlayer player1;
    MediaPlayer player2;

    final String TAG="MyService";
    public MyService() {

    }

    @Override
    public void onCreate() {
        Log.i(TAG,"onCreate");
        Toast.makeText(this,"创建了后台服务程序",Toast.LENGTH_LONG).show();
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG,"onStartCommand");
        Toast.makeText(this,"开始后台服务程序",Toast.LENGTH_LONG).show();

        //在这里拿到MainActivity中传递的数据
        if(intent.getExtras().get("music").equals("R.raw.by21")){
            player1=MediaPlayer.create(this,R.raw.by21);
            player1.start();
        }else{
            player2=MediaPlayer.create(this,R.raw.by22);
            player2.start();
        }

        Toast.makeText(this,"正在播放音乐",Toast.LENGTH_LONG).show();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Log.i(TAG,"onDestroy");
        Toast.makeText(this,"销毁后台服务程序",Toast.LENGTH_LONG).show();
        if(player1!=null){
            player1.release();
            player1=null;
        }
        if(player2!=null){
            player2.release();
            player2=null;
        }
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG,"onBind");
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG,"onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        Log.i(TAG,"onRebind");
        super.onRebind(intent);
    }
}